// request.js
import axios from 'axios'
import { ElMessage, ElMessageBox  } from "element-plus";

const service = axios.create({
    headers: {
        // todo 修改所以的请求方式的ContentType
        'Content-Type': 'application/json;charset=UTF-8'
    },
    baseURL: process.env.NODE_ENV === 'development' ? '' : '/' ,
    // 是否跨站点访问控制请求
    withCredentials: false,
    timeout: 60000,
    //请求数据转换
    transformRequest: [(data) => {
        return JSON.stringify(data)
    }],
    //相应数据转换
    transformResponse: [(data) => {
        if (typeof data === 'string' && data.startsWith('{')) {
            data = JSON.parse(data)
        }
        return data
    }]
})

// 请求拦截器
service.interceptors.request.use((config) => {
    try {
    let userInfo = window.localStorage.getItem('userInfo')
    if (userInfo) {
        let token = JSON.parse(userInfo).token
        // 注意：token前边有 'Bearer ' 的信息前缀,API接口需求，Bearer后边有空格
        config.headers={
            Accept: 'application/json, text/plain, */*',
            "Token":token,
            ...config.headers
        }

    }
    } catch (error) {
        
    }
    return config

}, (error) => {
    // 错误抛到业务代码
    error.data = {}
    error.data.msg = '服务器异常，请联系管理员！'
    return Promise.resolve(error)
})

// 返回拦截器
service.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return response
        } else {
            ElMessage.error(response.data.msg);
            return Promise.reject()
        }
    },
    error => {
        let status = error.response.status
        let msg = error.response.data.msg
        ElMessage.error(msg)
        console.log("数采平台接口请求失败");
        console.log(msg);
        return Promise.reject();
    }
);
export default service;
